<?php

use Liriope\Component\Json\Json;

class Gallery {
    
    // @var Liriope\Component\Json\Json The JSON object
    private $json;
    // @var string The title of the gallery
    private $title;
    // @var array  A list of project IDs to use for the featured projects
    private $featured = array();
    // @var array  The gallery projects
    private $projects = array();
    // @var array  The tags used in all of the projects
    private $tags = array();

    /**
     * CONSTRUCTOR
     *
     * @param string $file The location of the JSON data file
     */
    public function __construct($file=NULL) {
        $this->json = new Json($file);
        $gallery = $this->json->get();

        $this->title = $gallery->title;

        foreach($gallery->projects as $key => $project) {
            $this->projects[$key] = new GalleryProject($key, $project);
        }

        foreach($gallery->featured as $featured) {
            $this->featured[] = $this->projects[$featured];
        }
    }

    public function getTitle()      { return $this->title; }
    public function getFeatured()   { return $this->featured; }
    public function getProjects()   { return $this->projects; }
    public function getProject($id) { return $this->projects[$id]; }
    public function getTags() {
        if(!empty($this->tags)) return $this->tags;

        $tags = array();
        foreach($this->projects as $project) {
            $tags = array_merge($tags, $project->getTags());
        }
        $this->tags = array_unique($tags);
        return $this->tags;
    }

    public function sortProjects() {
        uasort($this->projects, array('self','sortByDate'));
        return $this;
    }

    private static function sortByDate($a, $b) {
        $aDate = strtotime($a->getDate());
        $bDate = strtotime($b->getDate());
        if($aDate == $bDate) return 0;
        return ($aDate > $bDate) ? +1 : -1;
    }
}
